package main

import (
	"fmt"
	"time"
)

// 工作中常用worker pool(goroutine池)模式, 控制go routine的数量, 防止goroutine泄露和暴涨
func worker(id int, jobs <-chan int, results chan<- int) {
	for j := range jobs {
		fmt.Printf("worker:%d start job:%d\n", id, j)
		time.Sleep(time.Second)
		fmt.Printf("worker:%d end job:%d\n", id, j)
		results <- j * 2
	}
}

func main() {
	jobs := make(chan int, 100)
	results := make(chan int, 100)

	//开启3个goroutine
	for w := 1; w <= 3; w++ {
		go worker(w, jobs, results)
	}

	//100个任务
	for j := 1; j <= 100; j++ {
		jobs <- j
	}
	close(jobs)

	//输出结果
	for a := 1; a <= 100; a++ {
		<-results
	}
}
